package com.sys.server.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sys.server.common.config.CommonConfig;
import com.sys.server.common.constants.enums.ResultSetEnum;
import com.sys.server.common.model.R;
import com.sys.server.modules.controller.dto.ParticipantDto;
import com.sys.server.modules.controller.dto.ProjectCommentDto;
import com.sys.server.modules.controller.dto.ProjectDto;
import com.sys.server.modules.controller.vo.PageVo;
import com.sys.server.modules.controller.vo.ParticipantVo;
import com.sys.server.modules.controller.vo.ProDetailVo;
import com.sys.server.modules.entity.ParticipateEntity;
import com.sys.server.modules.entity.ProgressEntity;
import com.sys.server.modules.entity.ProjectEntity;
import com.sys.server.modules.entity.UserEntity;
import com.sys.server.modules.mapper.ParticipateMapper;
import com.sys.server.modules.mapper.ProgressMapper;
import com.sys.server.modules.mapper.ProjectMapper;
import com.sys.server.modules.mapper.UserMapper;
import com.sys.server.modules.service.FileService;
import com.sys.server.modules.service.ProjectService;
import com.sys.server.modules.service.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.swing.*;
import java.util.Date;
import java.util.List;

@Service
public class ProjectServiceImpl implements ProjectService {

    private static final Logger LOG = LoggerFactory.getLogger(ProjectServiceImpl.class);

    @Autowired
    private FileService fileService;

    @Resource
    private ProjectMapper projectMapper;

    @Resource
    private ParticipateMapper participateMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private ProgressMapper progressMapper;

    @Autowired
    private TokenService tokenService;

    @Override
    public R addProject(ProjectDto projectDto) {
        ProjectEntity entity = null;
        if (projectDto.getProjid() != null) {
            entity = projectMapper.selectById(projectDto.getProjid());
        } else {
            entity = new ProjectEntity();
        }
        entity.setName(projectDto.getName());
        entity.setMaintext(projectDto.getMaintext());
        Date date = new Date();
        entity.setReltime(date);
        entity.setIspublic(projectDto.getIspublic());
        entity.setReluser(tokenService.getCurrentUser());
        String paths = CommonConfig.getAppendix_path() + "/project/" + projectDto.getName();
        String path = fileService.fileUpload(projectDto.getFile(), paths);
        if (StringUtils.isNotBlank(path)) {
            entity.setAttachment(path);
        } else {
            LOG.error("获取附件路径错误，附件上传失败");
            return R.ok(ResultSetEnum.FAIL);
        }
        entity.setAttachment(path);
        if (projectDto.getProjid() == null) {
            try {
                int row = projectMapper.insert(entity);
                if (row == 1) {
                    addToparticipate(tokenService.getCurrentUser());
                    return R.ok(ResultSetEnum.SUCCESS);
                }
            } catch (Exception e) {
                LOG.error("新增学生作品错误" + e.getMessage());
                return R.ok(ResultSetEnum.FAIL);
            }
        } else {
            try {
                int row = projectMapper.updateById(entity);
                if (row == 1) {
                    return R.ok(ResultSetEnum.SUCCESS);
                } else {
                    return R.ok(ResultSetEnum.FAIL);
                }
            } catch (Exception e) {
                LOG.error("更新学生项目错误（带附件）" + e.getMessage());
                return R.ok(ResultSetEnum.FAIL);
            }
        }
        return null;
    }

    @Override
    public R getProList(Long pagenum, Long pagesize) {
        IPage<ProjectEntity> page = new Page<>(pagenum, pagesize);
        try {
            projectMapper.selectPage(page, null);
        } catch (Exception e) {
            LOG.error("分页获取项目列表查询错误");
            return R.ok(ResultSetEnum.FAIL);
        }
        PageVo result = new PageVo();
        result.setList(page.getRecords());
        result.setTotal(page.getTotal());
        result.setSize(pagesize);
        result.setCurrent(pagenum);
        return R.ok(ResultSetEnum.SUCCESS, result);
    }

    @Override
    public R getProListPersonal(Long pagenum, Long pagesize) {
        Page<ProjectEntity> page = new Page<>(pagenum, pagesize);
        String uid = tokenService.getCurrentUser();
        try {
            projectMapper.getProListProsonal(page, uid);
        } catch (Exception e) {
            LOG.error("查询当前用户相关项目错误" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
        PageVo result = new PageVo();
        result.setList(page.getRecords());
        result.setTotal(page.getTotal());
        result.setSize(pagesize);
        result.setCurrent(pagenum);
        return R.ok(ResultSetEnum.SUCCESS, result);
    }

    @Override
    public R getProInfoById(Long id) {
        ProjectEntity entity = projectMapper.selectById(id);
        if (entity != null) {
            return R.ok(ResultSetEnum.SUCCESS, entity);
        } else {
            return R.ok(ResultSetEnum.FAIL);
        }
    }

    @Override
    public R updateProInfo(ProjectDto projectDto) {
        Long projid = projectDto.getProjid();
        ProjectEntity entity = projectMapper.selectById(projid);
        entity.setName(projectDto.getName());
        entity.setMaintext(projectDto.getMaintext());
        entity.setIspublic(projectDto.getIspublic());
        try {
            int row = projectMapper.updateById(entity);
            if (row == 1) {
                return R.ok(ResultSetEnum.SUCCESS);
            } else {
                return R.ok(ResultSetEnum.FAIL);
            }
        } catch (Exception e) {
            LOG.error("更新项目信息失败（不带附件）" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
    }

    @Override
    public R addParticipant(ParticipantDto participantDto) {
        ParticipateEntity entity = new ParticipateEntity();
        String uid = participantDto.getUid();
        try {
            UserEntity userEntity = userMapper.selectOne(Wrappers.<UserEntity>query().eq("uid", uid));
            if (userEntity == null) {
                return R.ok(500, "用户名不存在");
            }
        } catch (Exception e) {
            return R.ok(ResultSetEnum.FAIL);
        }
        entity.setUid(participantDto.getUid());
        entity.setProjid(participantDto.getProjid());
        String role = participantDto.getRole() == null ? "" : participantDto.getRole();
        entity.setRole(role);
        try {
            int row = participateMapper.insert(entity);
            if (row == 1) {
                return R.ok(ResultSetEnum.SUCCESS);
            }
        } catch (Exception e) {
            LOG.error("添加项目成员报错" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
        return null;
    }

    @Override
    public R getProParticipant(Long projid) {
        String uid = tokenService.getCurrentUser();
        List<UserEntity> list = projectMapper.getProParticipants(projid, uid);
        return R.ok(ResultSetEnum.SUCCESS, list);
    }

    @Override
    public R deleteProParticipant(@RequestBody ParticipantDto participantDto) {
        String uid = participantDto.getUid();
        Integer projid = participantDto.getProjid();
        QueryWrapper<ParticipateEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid);
        wrapper.eq("projid", projid);
        try {
            int row = participateMapper.delete(wrapper);
            if (row == 1) {
                return R.ok(ResultSetEnum.SUCCESS);
            } else {
                return R.ok(ResultSetEnum.FAIL);
            }
        } catch (Exception e) {
            LOG.error("删除项目成员错误" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
    }

    @Override
    public R updateProRole(ParticipantDto participantDto) {
        // 获取当前用户名
        String uid = tokenService.getCurrentUser();
        QueryWrapper<ParticipateEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", uid).eq("projid", participantDto.getProjid());
        ParticipateEntity participateEntity = participateMapper.selectOne(wrapper);
        participateEntity.setRole(participantDto.getRole());
        try {
            participateMapper.update(participateEntity, wrapper);
        } catch (Exception e) {
            LOG.error("学生更新项目中个人角色信息错误" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
        return R.ok(ResultSetEnum.SUCCESS);
    }

    @Override
    public R addProgress(ProjectDto projectDto) {
        ProgressEntity entity = new ProgressEntity();
        entity.setProjid(projectDto.getProjid());
        String uid = tokenService.getCurrentUser();
        entity.setReluser(uid);
        Date date = new Date();
        entity.setReltime(date);
        entity.setMaintext(projectDto.getMaintext());
        entity.setAttachment("");
        if (projectDto.getFile() != null) {
            Long timeNow = System.currentTimeMillis();
            String now = String.valueOf(timeNow);
            String paths = CommonConfig.getAppendix_path() + "/progress/" + projectDto.getProjid()  + "_" + now;
            String path = fileService.fileUpload(projectDto.getFile(), paths);
            if (StringUtils.isNotBlank(path)) {
                entity.setAttachment(path);
            }
        }
        try {
            int row = progressMapper.insert(entity);
            if (row == 1) {
                return R.ok(ResultSetEnum.SUCCESS);
            } else {
                return R.ok(ResultSetEnum.FAIL);
            }
        } catch (Exception e) {
            LOG.error("添加项目动态错误===" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
    }

    @Override
    public R updateProComment(ProjectCommentDto projectCommentDto) {
        Long projid = projectCommentDto.getProjid();
        ProjectEntity entity = projectMapper.selectById(projid);
        entity.setScore(projectCommentDto.getScore());
        entity.setComment(projectCommentDto.getComment());
        try {
            int row = projectMapper.updateById(entity);
            if (row == 1) {
                return R.ok(ResultSetEnum.SUCCESS);
            } else {
                return R.ok(ResultSetEnum.FAIL);
            }
        } catch (Exception e) {
            LOG.error("修改评价失败" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }

    }

    /**
     * 将添加项目的用户添加到表中
     *
     * @param uid
     */
    private void addToparticipate(String uid) {
        QueryWrapper<ProjectEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("reluser", uid);
        wrapper.orderByDesc("reltime");
        List<ProjectEntity> projectList = projectMapper.selectList(wrapper);
        ProjectEntity project = projectList.get(0);
        Integer projid = project.getProjid();
        UserEntity user = userMapper.selectOne(Wrappers.<UserEntity>query().eq("uid", uid));
        String role = user.getRole();
        ParticipantDto participantDto = new ParticipantDto();
        participantDto.setProjid(projid);
        participantDto.setRole(role);
        participantDto.setUid(uid);
        try {
            addParticipant(participantDto);
        } catch (Exception e) {
            LOG.error("将项目创建人添加到participant错误" + e.getMessage());
        }
    }

    @Override
    public R getDetail(Long projid) {
        ProDetailVo result = new ProDetailVo();
        ProjectEntity entity = projectMapper.selectById(projid);
        result.setBasic(entity);
        List<ParticipantVo> userList = projectMapper.getProParticipants2(projid);
        result.setUserList(userList);
        QueryWrapper<ProgressEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("projid", projid);
        wrapper.orderByDesc("reltime");
        List<ProgressEntity> progressList = progressMapper.selectList(wrapper);
        result.setProgressList(progressList);
        return R.ok(ResultSetEnum.SUCCESS, result);
    }

    @Override
    public R deletePro(ProjectDto projectDto) {
        long projid = projectDto.getProjid();
        try {
            projectMapper.deleteById(projid);
        } catch (Exception e) {
            LOG.error("删除项目project表错误" + e.getMessage());
            return R.ok(ResultSetEnum.FAIL);
        }
//        try {
//            participateMapper.delete(Wrappers.<ParticipateEntity>query().eq("projid", projid));
//        } catch (Exception e) {
//            LOG.error("删除项目participant表报错" + e.getMessage());
//            return R.ok(ResultSetEnum.FAIL);
//        }
//        try {
//            progressMapper.delete(Wrappers.<ProgressEntity>query().eq("projid", projid));
//        } catch (Exception e) {
//            LOG.error("删除项目progress表报错" + e.getMessage());
//        }
        return R.ok(ResultSetEnum.SUCCESS);
    }

    @Override
    public String getAttachPath(Long projid) {
        ProjectEntity entity = projectMapper.selectById(projid);
        return entity.getAttachment();
    }
}
